package com.atguigu.edu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.MyKafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

/**
 * @author:Rzd
 * @Date:2022年10月15日 09:08
 * @Description:
 */
public class DwdTrafficUniqueVisitorDetail {
    public static void main(String[] args) throws Exception{
        // TODO: 2022/10/15 1. 基本环境的准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        // TODO: 2022/10/15 2. 检查点的相关设置
        // TODO: 2022/10/15 3. 从kafka的page——log主题中读取数据
        //3.1声明消费的主题以及消费者组
        String topic = "dwd_traffic_page_log";
        String groupId = "dwd_traffic_uv_group";
        //3.2创建消费者对象
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getKafkaConsumer(topic, groupId);
        //3.3消费数据 封装为流
        DataStreamSource<String> kafkaStrDS = env.addSource(kafkaConsumer);
        // TODO: 2022/10/15 4. 对读取的数据进行类型转换
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.map(JSON::parseObject);
        // TODO: 2022/10/15 5. 按照mid分组
        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));
        // TODO: 2022/10/15 6. 使用flink状态变成 过滤出独立访客
        SingleOutputStreamOperator<JSONObject> filterDS = keyedDS.filter(
                new RichFilterFunction<JSONObject>() {
                    private ValueState<String> lastVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("lastVisitDateState", String.class);
                        valueStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1)).build());
                        lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        //获取上级页面id
                        String lastPageId = null;
                        try {
                            lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                        } catch (Exception e) {
//                            e.printStackTrace();
                            return false;
                        }
                        if (StringUtils.isNotEmpty(lastPageId)) {
                            return false;
                        }
                        //获取当前设备上次访问日期
                        String lastVisitDate = lastVisitDateState.value();
                        String curVisitDate = DateFormatUtil.toDate(jsonObj.getLong("ts"));

                        if (StringUtils.isEmpty(lastVisitDate) || !lastVisitDate.equals(curVisitDate)) {
                            lastVisitDateState.update(curVisitDate);
                            return true;
                        }
                        return false;


                    }
                }
        );
        filterDS.print(">>>");
        // TODO: 2022/10/15 7. 将过滤出的独立访客输出到kafka的主题中
        filterDS
                .map(jsonObj->jsonObj.toJSONString())
                .addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_unique_visitor_detail"));
        env.execute();
    }
}
